import Net from './net/Net'
import Packet from './net/Packet'
import GoodsItem from './pb/GoodsItem'
import Msg from './pb/Msg'
import RoleLogin from './pb/RoleLogin'
import RoleLoginOk from './pb/RoleLoginOk'

const { ccclass } = cc._decorator


@ccclass
export default class NewClass extends cc.Component {
    private _net: Net


    protected onLoad(): void {
        this._net = new Net(() => this.onNetOpen(), () => this.onNetClose(), () => this.onNetError())

        this._net.on(Msg.ROLE_LOGIN_OK, this.handleNet, this)
        this._net.on(Msg.GOODS_ITEM, this.handleNet, this)
    }

    protected start(): void {
        this.netConnect()
    }


    private netConnect() {
        this._net.connect('127.0.0.1', 8889)
    }

    private onNetOpen() {
        const roleLogin = new RoleLogin('admin', 'admin')
        this._net.send(roleLogin.encode())

        const roleLogin2 = new RoleLogin('root', 'root', '备注', new Uint8Array([66, 88, 99]))
        this._net.send(roleLogin2.encode())
    }

    private onNetClose() {

    }

    private onNetError() {

    }

    private handleNet(packetId: number, packet: Packet): void {
        console.log('协议 ID:' + packetId)
        switch (packetId) {
            case Msg.ROLE_LOGIN_OK:
                const roleLoginOk = RoleLoginOk.decode(packet)
                console.log('登录成功:', roleLoginOk)
                break
            case Msg.GOODS_ITEM:
                const goodsItem = GoodsItem.decode(packet)
                console.log('物品数据:', goodsItem)
                break
        }
    }
}
